﻿using System;
using System.Data.SQLite;
using System.Linq;
using System.Windows.Forms;
using Dapper;

namespace SoftLab.Formularios
{
    public partial class BuscarPaciente : SoftLab.Template.Template
    {
        public int PacienteId { get; set; }

        public BuscarPaciente()
        {
            InitializeComponent();
            Cargar();
            #region Close form
            label2.Click += (sender, e) => Close();
            #endregion
            #region Form KeyPress
            this.KeyDown += (sender, e) =>
            {
                if (e.KeyCode == Keys.Escape) Close();
            };
            #endregion
            #region DataGridView Click
            dataGridView1.CellContentClick += (sender, e) =>
            {
                if (dataGridView1.CurrentRow != null)
                {
                    PacienteId = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value);
                    Close();
                }
            };
            #endregion
            #region pacientesText TextChanged
            pacientesText.TextChanged += (sender, e) => Cargar(pacientesText.Text);
            #endregion
        }

        void Cargar()
        {
            using (var conexion = new SQLiteConnection(Properties.Settings.Default.ConnectionString))
            {
                conexion.Open();
                var q = "select id, nombre, apellido, direccion, telefono from pacientes";
                var query = conexion.Query<Clases.Pacientes>(q);
                var pacientes = query.ToList();
                dataGridView1.DataSource = pacientes;
                dataGridView1.Columns[0].Visible = false;
                dataGridView1.Columns[3].Visible = false;
                dataGridView1.Columns[4].Visible = false;
                conexion.Close();
            }
        }

        void Cargar(string nombre)
        {
            using (var conexion = new SQLiteConnection(Properties.Settings.Default.ConnectionString))
            {
                conexion.Open();
                var q = "select id, nombre, apellido, direccion, telefono from pacientes where nombre like @Nombre";
                var query = conexion.Query<Clases.Pacientes>(q, new { Nombre = "%" + nombre + "%" });
                var pacientes = query.ToList();
                dataGridView1.DataSource = pacientes;
                dataGridView1.Columns[0].Visible = false;
                dataGridView1.Columns[3].Visible = false;
                dataGridView1.Columns[4].Visible = false;
                conexion.Close();
            }
        }
    }
}
